//
//  HttpRequest.m
//  IM_LearningGYDF
//
//  Created by gydf on 16/3/10.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "HttpRequest.h"
#import "XMLReader.h"
#import "XMLDictionary.h"

@implementation HttpRequest
#pragma mark -- GET --
+ (void)getWithURLString:(NSString *)URLString
              parameters:(id)parameters
                 success:(void (^)(id))success failure:(void (^)(NSError *))failure {
//    HUD_HIDE
//    HUD_SHOW(HUD_PLEASEWAIT);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /** *
     */
    manager.responseSerializer = [AFJSONResponseSerializer serializer];
    /** *
     */
    manager.operationQueue.maxConcurrentOperationCount = 5;
    /** *
     */
    manager.requestSerializer.timeoutInterval = 5;

    [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //HUD_HIDE
        if (success) {
            success(responseObject);
        }
        NSLog(@"dict:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //HUD_HIDE
        if (failure) {
            failure(error);
        }
        NSLog(@"%@",error);
    }];
}

#pragma mark -- POST --
+ (void)postWithURLString:(NSString *)URLString
               parameters:(id)parameters
         success:(void (^)(id responseObject))success
                  failure:(void (^)(NSError *error))failure{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    /** *
     */
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    //manager.requestSerializer=[AFHTTPRequestSerializer serializer];
//    HUD_HIDE
//    HUD_SHOW(HUD_PLEASEWAIT);
    
//    NSString *soapStr = [NSString stringWithFormat:
//                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
//                         <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
//                         <soap:Body>\
//                         <Login xmlns=\"http://www.jjkj.com/\">\
//                         <content>%@</content>\
//                         </Login>\
//                         </soap:Body>\
//                         </soap:Envelope>",parameters];
    NSString *soapStr = [NSString stringWithFormat:
                          @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
                          <string xmlns=\"http://www.jjkj.com/\">%@</string>",parameters];
//
//    ((AFJSONResponseSerializer *)manager.responseSerializer).removesKeysWithNullValues=YES;
    [manager POST:URLString parameters:soapStr progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSError *parseError = nil;
        NSString *xmlStr=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:xmlStr error:&parseError];
        NSString *jsonStr=xmlDictionary[@"string"][@"text"];
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
////        //NSDictionary转换为Data
//        NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonStr options:NSJSONWritingPrettyPrinted error:&parseError];
//        
//        //Data转换为JSON
//        NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
        
        if (success) {
            success(dic);
        }
        NSLog(@"dict:%@",dic);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //HUD_HIDE
        if (failure) {
            failure(error);
        }
        NSLog(@"%@",error);
    }];
}

/*
 NSString *soapStr = [NSString stringWithFormat:
 @"<?xml version=\"1.0\" encoding=\"utf-8\"?>\
 <soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\
 <soap:Body>\
 <Login xmlns=\"http://www.jjkj.com/\">\
 <content>{\n  \"equipmentId\" : \"B9669D70-F03D-458D-AC69-5094FB3ABFF2\",\n  \"username\" : \"yanghq\",\n  \"password\" : \"1\"\n}\"</content>\
 </Login>\
 </soap:Body>\
 </soap:Envelope>"];
 */

+ (void)SOAPData:(NSString *)url SoapMthod:(NSString *)soapMthod soapBody:(NSString *)soapBody
         success:(void (^)(id responseObject))success failure:(void(^)(NSError *error))failure{

    NSString *soapStr = [NSString stringWithFormat:
                         @"<?xml version=\"1.0\" encoding=\"utf-8\"?>"
                         "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n"
                         "<soap:Body>\n"
                         "<%@ xmlns=%@>\n"
                         "%@\n"
                         "</%@>\n"
                         "</soap:Body>\n"
                         "</soap:Envelope>",@"ServiceRequest",NAMESPACE,soapBody,@"ServiceRequest"];

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFXMLParserResponseSerializer serializer];

    // 设置请求超时时间
    manager.requestSerializer.timeoutInterval = 30;

    // 返回NSData
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];

    //    // 设置请求头，也可以不设置
    [manager.requestSerializer setValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [manager.requestSerializer setValue:[NSString stringWithFormat:@"%zd", soapStr.length] forHTTPHeaderField:@"Content-Length"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/xml", nil];
    // 设置HTTPBody
    [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString *(NSURLRequest *request, NSDictionary *parameters, NSError *__autoreleasing *error) {
        return soapStr;
    }];
    NSLog(@"%@---soapStr------->%@",soapMthod,soapStr);
    [manager POST:url parameters:soapStr progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nonnull responseObject) {
        NSError *error=nil;
        NSString *xmlStr=[[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
        NSDictionary *xmlDictionary = [XMLReader dictionaryForXMLString:xmlStr error:&error];
        NSString *jsonStr=xmlDictionary[@"soap:Envelope"][@"soap:Body"][[NSString stringWithFormat:@"ServiceRequestResponse"]][[NSString stringWithFormat:@"ServiceRequestResult"]][@"text"];
        NSData *jsonData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
        NSError *err;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                            options:NSJSONReadingMutableContainers
                                                              error:&err];
        // 请求成功并且结果有值把结果传出去
        if (success && dic) {
            NSData* jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:nil];
            NSString* str = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
             NSLog(@"%@---dic------->%@",soapMthod,str);
            success(dic);
            return;
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideLoadViewWithView:kWindow];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [MBProgressHUD postMessageWithText:INTERNET_ERROR View:kWindow];
        });
        
        
        if (failure) {
            failure(error);
        }
        NSLog(@"%@",error.userInfo);
    }];
}
#pragma mark -- POST/GET --
+ (void)requestWithURLString:(NSString *)URLString
                  parameters:(id)parameters
                        type:(HttpRequestType)type
                     success:(void (^)(id))success failure:(void (^)(NSError *))failure{
    //HUD_SHOW(HUD_PLEASEWAIT);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSLog(@"url:%@\n dict:%@",URLString,parameters);
    switch (type) {
        case HttpRequestTypeGet:
        {
            [manager GET:URLString parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //HUD_HIDE
                if (success) {
                    success(responseObject);
                }
                NSLog(@"dict:%@",responseObject);

            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                //HUD_HIDE
                if (failure) {
                    failure(error);
                }
                NSLog(@"%@",error);
            }];
        }
            break;
        case HttpRequestTypePost:
        {
            [manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                //HUD_HIDE
                if (success) {
                    success(responseObject);
                }
                NSLog(@"dict:%@",responseObject);
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
               // HUD_HIDE
                if (failure) {
                    failure(error);
                }
                NSLog(@"%@",error);
            }];
        }
            break;

            
        default:
            break;
    }
}

#pragma mark -- --
+ (void)uploadWithURLString:(NSString *)URLString parameters:(id)parameters
                uploadParam:(UploadParam *)uploadParam
                    success:(void (^)(id responseObject))success
                    failure:(void (^)(NSError *error))failure
{
    //HUD_SHOW(HUD_PLEASEWAIT);
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializer];

    NSLog(@"url:%@\n dict:%@",URLString,parameters);
    [manager POST:URLString parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:uploadParam.data name:uploadParam.name fileName:uploadParam.filename mimeType:uploadParam.mimeType];
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //HUD_HIDE
        if (success) {
            success(responseObject);
        }
        NSLog(@"dict:%@",responseObject);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //HUD_HIDE
        if (failure) {
            failure(error);
        }
        NSLog(@"%@",error);
    }];

}
/** * *
 * @param   urlString   请求的网址字符串
 * @param   success     下载成功的回调
 * @param   failure     下载失败的回调
 */
+ (void)downLoadWithUrlString:(NSString *)urlString
                     failPath:(NSString *)filePath
                      success:(void (^)(id responseObject))success
                      failure:(void(^)(NSError *error))failure

{
    // 1.创建管理者对象
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 2.设置请求的URL地址
    NSURL *url = [NSURL URLWithString:urlString];
    // 3.创建请求对象
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    // 4.下载任务
    NSURLSessionDownloadTask *task = [manager downloadTaskWithRequest:request progress:^(NSProgress * _Nonnull downloadProgress) {
        // 下载进度
        NSLog(@"当前下载进度为:%lf", 1.0 * downloadProgress.completedUnitCount / downloadProgress.totalUnitCount);
    } destination:^NSURL * _Nonnull(NSURL * _Nonnull targetPath, NSURLResponse * _Nonnull response) {
        // 下载地址
        NSLog(@"默认下载地址%@",targetPath);
        // 设置下载路径,通过沙盒获取缓存地址,最后返回NSURL对象
        return [NSURL fileURLWithPath:filePath]; // 返回的是文件存放在本地沙盒的地址
    } completionHandler:^(NSURLResponse * _Nonnull response, NSURL * _Nullable filePath, NSError * _Nullable error) {
        // 下载完成调用的方法
        NSLog(@"%@---%@", response, filePath);
        
        if (success) {
            success(response);
        }
        
        
    }];
    // 5.启动下载任务
    [task resume];  }
//检测网络状况
+ (BOOL)isNotNetwork
{
    __block BOOL isExistenceNetwork = NO;
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
                //未知网
                isExistenceNetwork = YES;

                break;
            case AFNetworkReachabilityStatusNotReachable:
                //无网
                isExistenceNetwork = YES;

                break;
            case AFNetworkReachabilityStatusReachableViaWWAN:
                //蜂窝数据网, 无线网
                isExistenceNetwork = NO;

                break;
            case AFNetworkReachabilityStatusReachableViaWiFi:
                //wifi网
                isExistenceNetwork = NO;
                break;
            default:
                break;
        }

    }];
    return isExistenceNetwork;
}


@end
